﻿using Lazy.Captcha.Core.Generator.Code;
using Lazy.Captcha.Core.Generator.Extensions;
using Lazy.Captcha.Core.Generator.Image.Option;
using Lazy.Captcha.Core.Interface;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper.Config;

namespace Lazy.Captcha.Core.Config
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class VerCodeConfig : IVerCodeConfig
    {
        private const int DEFAULT_CODE_LENGTH = 4;

        protected VerCodeConfig ( IConfigCollect config, string key )
        {
            IConfigSection section = config.GetSection("Hr:" + key);
            section.AddRefreshEvent(this._Init);
        }

        private void _Init ( IConfigSection section, string name )
        {
            this.CaptchaType = section.GetValue<CaptchaType>("CaptchaType", CaptchaType.DEFAULT);
            this.CodeLength = section.GetValue<int>("CodeLength", DEFAULT_CODE_LENGTH);
            int expir = section.GetValue<int>("ExpirySeconds", 60);
            this.ExpirySeconds = new TimeSpan(0, 0, expir);
            this.IgnoreCase = section.GetValue<bool>("IgnoreCase", true);
            this.ImageOption = section.GetValue<CaptchaImageGeneratorOption>("ImageOption", new CaptchaImageGeneratorOption());
            this.CodeGenerator = new DefaultCaptchaCodeGenerator(this);
            if ( this.CaptchaType.IsArithmetic() )
            {
                // 当是4时，长度重置为2。不过四位数的运算用户体验不佳，因此不必在意这个bug。
                if ( this.CodeLength == DEFAULT_CODE_LENGTH )
                {
                    this.CodeLength = 2;
                }
            }
            if ( this.CaptchaType.ContainsChinese() )
            {
                this.ImageOption.FontFamily = DefaultFontFamilies.Kaiti;
            }

        }
        /// <summary>
        /// 验证码类型
        /// </summary>
        public CaptchaType CaptchaType
        {
            get;
            private set;
        }

        /// <summary>
        /// 验证码长度
        /// </summary>
        public int CodeLength { get; private set; } = DEFAULT_CODE_LENGTH;

        /// <summary>
        /// 过期时长
        /// </summary>
        public TimeSpan ExpirySeconds { get; private set; }

        /// <summary>
        /// code比较是否忽略大小写
        /// </summary>
        public bool IgnoreCase { get; set; } = true;

        /// <summary>
        /// 图片选项
        /// </summary>
        public CaptchaImageGeneratorOption ImageOption { get; private set; }

        /// <summary>
        /// Code生成器
        /// </summary>
        public ICaptchaCodeGenerator CodeGenerator { get; private set; }
    }
}
